package com.hd.trans.ui.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter.AnimationType
import com.hd.trans.R
import com.hd.trans.TranslationInterior
import com.hd.trans.binding.visible
import com.hd.trans.common.interf.Callback
import com.hd.trans.databinding.ActivityPictureTransHistoryBinding
import com.hd.trans.db.DataBaseMgr
import com.hd.trans.db.bean.FileTranslateRecord
import com.hd.trans.framework.dialog.ConfirmDialog
import com.hd.trans.framework.dialog.RecordMenuDialog
import com.hd.trans.framework.dialog.RenameDialog
import com.hd.trans.framework.dialog.ServiceObjectListener
import com.hd.trans.framework.dialog.Worker
import com.hd.trans.framework.dialog.WorkerType
import com.hd.trans.limit4Use.LimitUseListener
import com.hd.trans.ui.adapter.RecordPictureAdapter
import com.hd.trans.ui.base.BaseActivity
import com.hd.trans.ui.model.PictureTransModel
import com.hd.trans.utils.SharedFileUtils
import com.hd.trans.utils.ToastUtils
import com.hd.trans.utils.TrackerForTrans

class PictureTransHistoryActivity: BaseActivity() {

    private var dialog: ConfirmDialog? = null
    private lateinit var adapter: RecordPictureAdapter
    lateinit var mDataBinding: ActivityPictureTransHistoryBinding
    lateinit var mDataModel: PictureTransModel

    override fun getLayoutId(): Int {
        return R.layout.activity_picture_trans_history
    }

    companion object {

        @JvmStatic
        var limitListener: LimitUseListener? = null
        @JvmStatic
        var callback: Callback? = null

        @JvmStatic
        fun open(context: Context, listener: LimitUseListener?) {
            limitListener = listener
            val intent = Intent(context, PictureTransHistoryActivity::class.java)
            context.startActivity(intent)
        }

        @JvmStatic
        fun open(context: Context, listener: LimitUseListener?, callback: Callback? = null) {
            limitListener = listener
            this.callback = callback
            val intent = Intent(context, PictureTransHistoryActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val recordMenuDialog by lazy {
        RecordMenuDialog().apply {
            setOnItemClickListener(object : ServiceObjectListener {
                override fun onServiceObjectListener(
                    baseQuickAdapter: BaseQuickAdapter<*, *>,
                    view: View,
                    position: Int,
                    record: FileTranslateRecord?,
                    recordPosition: Int,
                ) {
                    val data: Worker = baseQuickAdapter.data[position] as Worker
                    when (data.type) {
                        WorkerType.share -> {
                            SharedFileUtils.shareFile(activity, record?.translateFilePath)
                            /*ShareUtil.shareFile(
                                activity,
                                File(record?.translateFilePath),
                                activity?.getString(R.string.share_file)
                            )*/
                            dismiss()
                        }
                        WorkerType.rename -> {
                            //重命名
                            RenameDialog(record?.fileName).apply {

                                clickRight = {
                                    record?.fileName = it
                                    DataBaseMgr.getInstance().updateFileTranslateRecord(record)
                                    adapter.notifyItemChanged(recordPosition)
                                }

                            }.show(supportFragmentManager, "Rename")
                        }
                        WorkerType.delete -> {
                            mDataModel.deleteFileTranslateRecord(record){
                                adapter.remove(recordPosition)
                            }
                            dismiss()
                        }
                    }
                }
            }
            )

        }
    }

    override fun initViewsAndEvents(savedInstanceState: Bundle?) {
        super.initViewsAndEvents(savedInstanceState)
        //视图埋点
        TranslationInterior.getTrackerListener().view("${TrackerForTrans.PZFY}历史记录页面")
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_picture_trans_history)
        mDataModel = ViewModelProvider(this).get(PictureTransModel::class.java)

        initView()
        initData()
    }

    private fun initView() {
        mDataBinding.apply {
            layoutTitle.rightText.text = getString(R.string.history_manager)
            layoutTitle.tilte.text = getString(R.string.photo_translate_history)
            layoutTitle.rightText.visible = true

            layoutTitle.back.setOnClickListener {
                finish()
            }

            layoutTitle.rightText.setOnClickListener {
                val rightTextStr: String = layoutTitle.rightText.text.toString()
                if(adapter.isManagerType){
                    if (rightTextStr == resources.getString(R.string.select_all)) {
                        //全选
                        adapter.selectAll { selectedAllStatus() }
                    } else if (rightTextStr == resources.getString(R.string.cancel_select_all)) {
                        //取消全选
                        adapter.cancelSelectAll { cancelSelectedAllStatus() }
                    }
                }else{
                    //进入管理
                    entryManagerStatus()
                }
            }

            layoutTitle.leftText.setOnClickListener {
                //退出管理
                adapter.cancelSelectAll { exitManagerStatus() }
            }

            tvDeleteItems.setOnClickListener {
                //移出文本翻译记录/收藏夹

                //移出文本翻译记录/收藏夹
                if (adapter.data.size == 0) {
                    ToastUtils.showNormal("没有任何收藏记录")
                    return@setOnClickListener
                }
                if (dialog == null) {
                    dialog = ConfirmDialog.builder()
                        .setContent(resources.getString(R.string.confirm_tip))
                        .rightTxtColor(TranslationInterior.getThemeColor())
                        .setRightListenner {
                            val records = adapter.selectedData
                            mDataModel.deleteFileTranslateRecords(records){
                                ToastUtils.showNormal("已删除${getString(R.string.photo_translate_history)}")
                                tvDeleteItems.isEnabled = false
                                tvDeleteItems.setBackgroundResource(R.drawable.shape_corner_cccccc_16)
                                adapter.selectedData.clear()
                                exitManagerStatus()
                                mDataModel.getFileTranslateRecord()
                            }
                        }
                        .build()
                }
                dialog?.show(supportFragmentManager, "PictureTransHistoryActivity")
            }

            setAdapter()
        }

        mDataModel.getFileTranslateRecord()
    }

    private fun setAdapter() {
        mDataBinding.recyclerView.layoutManager = LinearLayoutManager(this)
        mDataBinding.recyclerView.itemAnimator = DefaultItemAnimator()
        adapter = RecordPictureAdapter(null)
        adapter.animationEnable = true
        adapter.setAnimationWithDefault(AnimationType.SlideInBottom)
        mDataBinding.recyclerView.adapter = adapter
        adapter.setEmptyView(R.layout.layout_empty)

        adapter.setOnItemChildClickListener { baseAdapter, view, position ->
            //
            when(view.id){
                R.id.rl_item -> {
                    if (adapter.isManagerType) {
                        view.findViewById<View>(R.id.check_box).performClick()
                    } else {
                        PictureTransResultActivity.open(
                            this@PictureTransHistoryActivity,
                            null,
                            this.adapter.data[position].createTime,
                            limitListener,
                            callback
                        )
                    }
                }
                R.id.iv_point -> recordMenuDialog.setServiceObject(
                    this.adapter.data[position],
                    position)
                    .show(supportFragmentManager, "SelectLanguageDialog")
            }
        }

        adapter.setOnItemLongClickListener { baseQuickAdapter, view, position ->
            if (!adapter.isManagerType) {
                entryManagerStatus()
                adapter.setItemLongClickPosition(position)
            }
            false
        }

        adapter.setCallbackListener {
            if (adapter.data.size == adapter.selectedData.size) {
                //全选状态
                selectedAllStatus()
            } else {
                //非全选状态
                cancelSelectedAllStatus()
            }
        }
    }

    private fun initData() {
        mDataModel.listFileTranslateRecord.observe(this
        ) { records: List<FileTranslateRecord>? ->
            if (records != null) {
                //
                adapter.setList(records)
                mDataBinding.layoutTitle.rightText.visible = records.isNotEmpty()
            }
        }
    }

    private fun entryManagerStatus() {
        mDataBinding.layoutTitle.leftText.text = resources.getString(R.string.history_exit_manager)
        mDataBinding.layoutTitle.back.visibility = View.GONE
        mDataBinding.layoutTitle.leftText.visibility = View.VISIBLE
        mDataBinding.flBottom.visibility = View.VISIBLE
        mDataBinding.tvDeleteItems.isEnabled = false
        mDataBinding.layoutTitle.rightText.text = resources.getString(R.string.select_all)
        mDataBinding.layoutTitle.rightText.setTextColor(resources.getColor(R.color.primary_color))
        adapter.setShowType(true)
        adapter.notifyDataSetChanged()
    }

    private fun exitManagerStatus() {
        adapter.setShowType(false)
        mDataBinding.layoutTitle.back.visibility = View.VISIBLE
        mDataBinding.layoutTitle.leftText.visibility = View.GONE
        mDataBinding.flBottom.visibility = View.GONE
        mDataBinding.layoutTitle.rightText.text = resources.getString(R.string.history_manager)
        mDataBinding.layoutTitle.rightText.setTextColor(resources.getColor(R.color.primary_text_black))
    }

    private fun selectedAllStatus() {
        //全选
        mDataBinding.tvDeleteItems.isEnabled = true
        mDataBinding.tvDeleteItems.setBackgroundResource(R.drawable.shape_corner_blue_16)
        mDataBinding.layoutTitle.rightText.text = resources.getString(R.string.cancel_select_all)
    }

    private fun cancelSelectedAllStatus() {
        //取消全选
        mDataBinding.layoutTitle.rightText.text = resources.getString(R.string.select_all)
        if (adapter.selectedData.size == 0) {
            mDataBinding.tvDeleteItems.isEnabled = false
            mDataBinding.tvDeleteItems.setBackgroundResource(R.drawable.shape_corner_cccccc_16)
        } else {
            mDataBinding.tvDeleteItems.isEnabled = true
            mDataBinding.tvDeleteItems.setBackgroundResource(R.drawable.shape_corner_blue_16)
        }
    }
}